<template>
  <div class="server-main">
    <el-form
      :model="dynamicValidateForm"
      ref="dynamicValidateForm"
      class="demo-dynamic"
    >
      <el-form-item
        class="dynamic-item"
        v-for="item in dynamicValidateForm.infos"
        :key="item.id"
      >
        <el-input
          v-model="item.value"
          :disabled="!!exceptionId"
          placeholder="请输入异常信息"
        ></el-input>
        <el-button
          type="danger"
          :disabled="!!exceptionId"
          @click.prevent="removeUnusualInfo(item)"
          >删除</el-button
        >
      </el-form-item>
      <el-form-item class="item">
        <el-button
          type="primary"
          :disabled="!!exceptionId"
          @click="addUnusualInfo"
          >新增</el-button
        >
      </el-form-item>
    </el-form>

    <div class="server-table">
      <div class="table-title">
        <span class="table-title-text"></span>
        <div>
          <el-button type="primary" size="small" @click="unusualAnalyse"
            >异常分析</el-button
          >
          <el-button
            v-show="showBtn"
            type="primary"
            size="small"
            @click="repeatCheck"
            >重复性检测</el-button
          >
          <el-button
            v-show="showBtn"
            type="primary"
            size="small"
            @click="clusterAnalyse"
            >聚类分析
          </el-button>
          <el-button type="primary" size="small" @click="repaireSchemeRec"
            >修复方案推荐</el-button
          >
        </div>
      </div>
      <el-table
        :data="tableList"
        class="km-table"
        v-show="!newArr"
        :row-class-name="testing ? tableRowClassName : ''"
      >
        <el-table-column
          prop="exceptionMessage"
          label="异常信息"
          align="center"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          prop="exceptionType"
          label="异常类型"
          align="center"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          prop="exceptionDefectLevel"
          label="异常严重程度"
          align="center"
          show-overflow-tooltip
        >
        </el-table-column>
      </el-table>
      <!-- <el-pagination background layout="prev, pager, next" :total="total" :hide-on-single-page="!total"
        :page-size="modelData.pageSize" :pager-count="11" :current-page="modelData.pageNum" prev-text="上一页"
        next-text="下一页" @current-change="handleCurrentChange">
      </el-pagination> -->

      <template v-for="item in newArr">
        <el-table :data="item" border :key="item" class="tableClass km-table">
          <el-table-column
            prop="exceptionMessage"
            label="异常信息"
            align="center"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column
            prop="exceptionType"
            label="异常类型"
            align="center"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column
            prop="exceptionDefectLevel"
            label="异常严重程度"
            align="center"
            show-overflow-tooltip
          >
          </el-table-column>
        </el-table>
      </template>
    </div>
  </div>
</template>

<script>
import { mapState, mapMutations } from "vuex";
export default {
  name: "intelligenceRec",
  components: {},
  data: () => {
    return {
      dynamicValidateForm: {
        infos: [
          {
            value: "",
            // id: 0, // 可写可不写
          },
        ],
      },
      showBtn: false,
      exceptionId: null,
      classFlag: [],
      testing: null,
      newArr: null, // 存储聚类分析结果的二维数组
      modelData: {
        name: "", // 需求内容
        pageNum: 1, // 页码
        pageSize: 10, // 每页条数
      },
      tableList: [], // 本体类别列表
      total: 0, // 数据总条数
    };
  },
  computed: {
    ...mapState({
      containerDom: (state) => state.server.containerDom,
    }),
  },
  watch: {
    "dynamicValidateForm.infos": {
      handler: function (newVal, oldVal) {
        if (this.dynamicValidateForm.infos.length > 1) {
          this.showBtn = true;
        } else {
          this.showBtn = false;
        }
      },
      immediate: true,
    },
  },
  created() {
    const { exceptionId } = this.$route.query;
    if (exceptionId) {
      this.exceptionId = exceptionId;
      this.getTableList();
    }
  },
  mounted() {},
  methods: {
    // 新增异常信息
    addUnusualInfo() {
      this.dynamicValidateForm.infos.push({
        value: "",
        id: Date.now(),
      });
    },
    // 移除异常信息
    removeUnusualInfo(item) {
      let index = this.dynamicValidateForm.infos.indexOf(item);
      if (index !== -1) {
        this.dynamicValidateForm.infos.splice(index, 1);
      }
    },

    // 查询
    onSubmit(pageNum) {
      this.modelData.pageNum = pageNum ? pageNum : this.modelData.pageNum;
    },

    // 获取列表数据
    async getTableList() {
      let params = {
        exceptionId: this.exceptionId,
      };
      let res = await this.$axios.post(
        this.$api.repaireSchemeRec.zehaoObj.selectByExceptionId,
        params
      );
      if (res.data.code !== 200) {
        this.$message.warning(res.data.message);
        return;
      }
      let arr = [];
      res.data.data.forEach((item) => {
        arr.push({
          value: item.exceptionMessage,
          id: item.detailId,
        });
        item.useMode = this.useMode;
        return item;
      });
      this.dynamicValidateForm.infos = arr;
      this.total = res.data.data.length;
      this.tableList = res.data.data;
    },

    // 修改当前页码
    handleCurrentChange(page) {
      this.modelData.pageNum = page;
    },

    // 异常分析
    async unusualAnalyse() {
      this.exceptionId = -1;
      let message = this.dynamicValidateForm.infos.map((item) => {
        return item.value;
      });
      let params = {
        exception_list: message,
      };
      let res = await this.$axios.post(
        this.$api.repaireSchemeRec.zehaoObj.exceptionAnalysis,
        params
      );
      if (res.data.code !== 200) {
        this.$message.warning(res.data.message);
        this.exceptionId = null;
        return;
      }
      // this.total = res.data.data.total;
      // this.tableList = res.data.data.list;
      this.tableList = res.data.data;
      if (res.data.data.length) {
        this.exceptionId = res.data.data[0].exceptionId;
      }
    },

    // 重复性检测
    repeatCheck() {
      this.newArr = null;
      this.testing = true;
    },

    // 待处理
    tableRowClassName({ row }) {
      // if (row.testFlag) {
      //   if (this.classFlag.indexOf(`line${row.testFlag}`) < 0) {
      //     this.classFlag.push(`line${row.testFlag}`);
      //   }
      //   this.getDom();
      //   return `line${row.testFlag}`;
      // }
      // this.classFlag.push('line0');
      // return 'line0';
      if (this.classFlag.indexOf(`line${row.testFlag}`) < 0) {
        this.classFlag.push(`line${row.testFlag}`);
      }
      this.getDom();
      return `line${row.testFlag}`;
    },

    getDom() {
      // 生成有 1000 种颜色的数组
      const color = this.getRandomColor(1000);
      this.classFlag.forEach((item) => {
        let dom = document.getElementsByClassName(item);
        if (dom.length) {
          Array.from(dom).forEach((n) => {
            n.style.backgroundColor = color[item.slice(-1)]
              ? color[item.slice(-1)]
              : color[0];
          });
        }
      });
    },

    // 生成随机色
    getRandomColor(num) {
      const arr = [];
      for (let j = 0; j < num; j++) {
        let str = "";
        const r = Math.floor(Math.random() * 256);
        const g = Math.floor(Math.random() * 256);
        const b = Math.floor(Math.random() * 256);
        str += "rgb(" + r + "," + g + "," + b + "," + 0.3 + ")";
        arr.push(str);
      }
      return arr;
    },

    // 聚类分析
    clusterAnalyse() {
      let mapObj = new Map();
      let newArr = new Array();
      this.tableList.forEach((item) => {
        // 目前的方案是如果没有 clusterFlag(或为 null) 就不处理
        if (!item.clusterFlag) {
          newArr = null;
        } else {
          if (!mapObj.get(item.clusterFlag)) {
            mapObj.set(item.clusterFlag, [item]);
          } else {
            mapObj.get(item.clusterFlag).push(item);
          }
        }
      });
      for (const [key, value] of mapObj) {
        newArr.push(value);
      }
      this.newArr = newArr;
    },
    // 修复方案推荐
    repaireSchemeRec() {
      this.$router.push("/repaireSchemeRec/repaireSchemeRec");
      // this.$router.push({
      //   path: "/repaireSchemeRec/repaireSchemeRec",
      //   query: {
      //     exceptionId: this.exceptionId ? this.exceptionId : null,
      //     unusualInfo: this.dynamicValidateForm.infos
      //   }
      // });
    },
  },
  beforeRouteLeave(to, from, next) {
    localStorage.setItem(
      "info",
      JSON.stringify(this.dynamicValidateForm.infos)
    );
    localStorage.setItem("exceptionId", JSON.stringify(this.exceptionId));
    next();
  },
};
</script>
<style lang="scss" scoped>
.server-main {
  position: relative;

  .demo-dynamic {
    background: #ffffff;
    border-radius: 4px;
    padding: 16px 32px;

    .dynamic-item ::v-deep .el-form-item__content {
      display: flex;

      .el-input {
        margin-right: 20px;
      }
    }

    .item {
      margin: 0 auto;
      display: flex;
      justify-content: center;
    }
  }

  .form-input ::v-deep .el-input {
    width: 250px;
    margin-right: 20px;
  }

  .server-table {
    margin-top: 16px;
    padding: 16px 32px 64px;
    background: #ffffff;
    border-radius: 4px;

    .table-title {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .table-title-text {
        margin: 8px 0;
        font-size: 16px;
        line-height: 16px;
        border-left: 5px solid $--color-primary;
        padding-left: 10px;
      }

      margin-bottom: 10px;
    }

    .tableClass {
      margin-bottom: 20px;
    }
  }

  .ontology-edit {
    padding: 0 10px;
    & + .ontology-edit {
      border-left: 1px solid #dddddd;
    }
  }

  ::v-deep .el-table__append-wrapper {
    padding: 10px;
  }

  ::v-deep .el-dialog {
    width: 500px;
    border-radius: 5px;
  }

  .dialog-inline {
    ::v-deep .el-form-item__content {
      width: 300px;
    }

    button.el-button {
      background-color: $--color-primary !important;
      color: #fff !important;
      line-height: 1.2;
    }
  }
}
</style>
